package com.chem.lems.serves.impl;

import com.chem.lems.constans.ResultCodeConstant;
import com.chem.lems.entity.User;
import com.chem.lems.repository.UserRepository;
import com.chem.lems.serves.LoginServies;
import com.chem.lems.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class LoginServiesImpl implements LoginServies {
    @Autowired
    private UserRepository userRepository;

    /**
     * 用户登录
     *
     * @param fromUser
     * @return
     */
    public ResultUtil login(User fromUser) {
        String userName = fromUser.getUsername();
        if (null == userName || "".equals(userName)) {
            return new ResultUtil(ResultCodeConstant.FAIL, "请输入用户名或密码！");
        }
        User result = userRepository.findByUserName(userName);
        if (null == result) {
            return new ResultUtil(ResultCodeConstant.FAIL, "用户不存在！");
        } else if (fromUser.getPassword().equals(result.getPassword())) {
            if (!result.isUserState()) {
                return new ResultUtil(ResultCodeConstant.UNAUTHORIZED, "该用户未激活，请联系管理员！");
            }
            Map map = new HashMap();
            map.put("user", result);
            // 生成token ，暂时使用UUID代替
            String token = UUID.randomUUID().toString().replaceAll("-", "");
            map.put("token", token);
            result.setLoginState(true);
            result.setLoginTime(new Date());
            userRepository.save(result);
            return new ResultUtil(ResultCodeConstant.SUCCESS, "登录成功！", map);
        }
        return new ResultUtil(ResultCodeConstant.FAIL, "用户名或密码不正确！");

    }

    @Override
    public ResultUtil outLogin(String userId) {
        User result = userRepository.findById(userId).get();
        if (null == result) {
            return new ResultUtil(ResultCodeConstant.FAIL, "退出异常，用户不存在！");
        }
        result.setLoginState(false);
        userRepository.save(result);
        return new ResultUtil(ResultCodeConstant.SUCCESS, "退出成功！");
    }
}
